const db = wx.cloud.database()
const app = getApp()

// 获取用户游戏记录
exports.get_record_list = (game_code, openid) => {
  console.log('get_record_list', openid)
  db.collection(game_code).where({
    _openid: openid
  }).get().then(res => {
    if (res.data.length == 0) {
      // 没有查询到用户记录，创建一条新记录
      console.log('create record')
      db.collection('ldtj').add({
        data: {
          openid: openid,
          game_code: game_code,
          login_time: new Date(),
          status: 0,
          record_list: [],
          tool_list: [],
          task: {},
          answer_list: {},
        }
      }).then(res => {
        // 创建新数据成功
        app.globalData.record_id = res._id
        app.globalData.record_list = []
        app.globalData.tool_list = []
        app.globalData.task = {}
        app.globalData.answer_list = []

        // 获取游戏基础信息
        exports.get_game_config(game_code)
      }).catch(res => {
        wx.showModal({
          title: '系统信息',
          content: '出错了' + res,
        })
      })
    } else {
      // 将用户历史记录数据保存到本地
      app.globalData.record_id = res.data[0]._id
      app.globalData.record_list = res.data[0].record_list
      app.globalData.tool_list = res.data[0].tool_list
      app.globalData.task = res.data[0].task
      app.globalData.answer_list = res.data[0].answer_list

      // 更新登录时间
      db.collection(game_code).doc(res.data._id).update({
          data: {
            login_time: new Date(),
          }
        }).then(res => {
          // 获取游戏基础信息
          exports.get_game_config(game_code)
        })
        .catch(console.error)
    }
  }).catch(res => {
    console.log('get error', res)
    wx.showModal({
      title: '系统信息',
      content: 'Error:' + res,
    })
  })
}

// 复位用户游戏记录（重玩）
exports.reset_record_list = () => {
  console.log('reset_record_list')
  let game_code = app.globalData.game_code
  let record_id = app.globalData.record_id

  // 更新本地游戏记录
  app.globalData.record_list = []
  app.globalData.tool_list = []
  app.globalData.task = {}
  app.globalData.answer_list = []

  // 更新远程游戏记录
  db.collection(game_code).doc(record_id).update({
      data: {
        update_time: new Date(),
        record_list: [],
        tool_list: [],
        task: {},
        answer_list: [],
      }
    }).then()
    .catch(console.error)

  //  重新载入远程游戏数据
  exports.get_game_config(game_code)
}

// 放弃关卡
exports.abort_checkpoint = (checkpoint_id) => {
  console.log('abort_checkpoint')
  let game_code = app.globalData.game_code
  let record_id = app.globalData.record_id

  // 更新本地任务记录
  app.globalData.task = {}

  // 更新远程任务记录
  db.collection(game_code).doc(record_id).update({
      data: {
        update_time: new Date(),
        task: {},
      }
    }).then(res => {
      // 更新游戏记录
      exports.set_checkpoint_status(checkpoint_id, 0)
    })
    .catch(console.error)
}

// 选择关卡
exports.select_checkpoint = (checkpoint_id) => {
  console.log('select_checkpoint')
  let game_code = app.globalData.game_code
  let record_id = app.globalData.record_id

  // 更新本地任务记录
  let task = {
    cid: checkpoint_id,
  }
  app.globalData.task = task

  // 更新远程任务记录
  db.collection(game_code).doc(record_id).update({
      data: {
        update_time: new Date(),
        task: task,
      }
    }).then(res => {
      // 更新游戏记录
      exports.set_checkpoint_status(checkpoint_id, 1)
    })
    .catch(console.error)
}

// 到达关卡
exports.find_checkpoint = (checkpoint_id) => {
  console.log('find_checkpoint')
  // 更新游戏记录
  exports.set_checkpoint_status(checkpoint_id, 2)
}

// 保存用户游戏记录
exports.set_checkpoint_status = (checkpoint_id, status) => {
  console.log('set_checkpoint', status)
  let game_code = app.globalData.game_code
  let record_list = app.globalData.record_list
  let record_id = app.globalData.record_id
  let checkpoint = app.globalData.config.checkpoint_list[checkpoint_id]

  // search checkpoint id from record list
  for (let key in record_list) {
    let record = record_list[key]
    if (record.id == checkpoint.id) {
      console.log('edit record')
      record.status = status

      // 更新用户记录
      db.collection(game_code).doc(record_id).update({
          data: {
            update_time: new Date(),
            record_list: record_list,
          }
        }).then()
        .catch(console.error)

      return
    }
  }

  // not found checkpoint
  console.log('add record')
  let record = {
    id: checkpoint.id,
    status: status,
  }
  record_list.push(record)

  // 更新用户记录
  db.collection(game_code).doc(record_id).update({
      data: {
        update_time: new Date(),
        record_list: record_list,
      }
    }).then()
    .catch(console.error)

}

// 获取游戏基础配置信息
exports.get_game_config = (code) => {
  // console.log('get_game_config', code)
  db.collection(code).doc('5bf39d400822e6114987b4da')
    .get().then(res => {
      app.globalData.config = res.data
      app.globalData.game_code = code
      console.log('get game config', app.globalData)
    })
}

// 初始化游戏记录
exports.init_record_list = () => {
  console.log('init_record_list')
  let checkpoint_list = app.globalData.config.checkpoint_list
  let record_list = app.globalData.record_list

  // 根据用户记录修改关卡状态
  for (let key in record_list) {
    let record = record_list[key]
    let checkpoint_id = record.id

    // 调整关卡状态
    if ('status' in record) {
      checkpoint_list[checkpoint_id].status = record.status
    }

    // 调整关卡是否显示
    if ('show' in record) {
      checkpoint_list[checkpoint_id].show = record.show
    }
  }

  // 根据状态，修改关卡显示图片
  for (let key in checkpoint_list) {
    let checkpoint = checkpoint_list[key]
    if (checkpoint.show) {
      // console.log(checkpoint)
      switch (checkpoint.status) {
        case 0:
          checkpoint.image = checkpoint.image0
          break
        case 1:
          checkpoint.image = checkpoint.image1
          break
        case 2:
          checkpoint.image = checkpoint.image2
          break
        case 3:
          checkpoint.image = checkpoint.image3
          break
        case 4:
          checkpoint.image = checkpoint.image4
          break
      }
    }
  }

}